<template>
    <view class="login">
        <!-- <u-navbar 
            :title="pageTitle" 
            :background="headerBg" 
            title-color="#ffffff"
        ></u-navbar> -->

        <view class="login-header">
            <view class="login-header-logo">
                <image src="/static/logo.png" mode="aspectFit"></image>
            </view>
        </view>

        <view class="login-form">
            <!-- 表单 -->
            <u-form :model="form" ref="formRef" :rules="rules" label-position="left" label-width="100rpx">
                <!-- 用户名/手机号 -->
                <u-form-item label="账号" prop="username">
                    <u-input v-model="form.phone" placeholder="请输入手机号">
                        <template #prefix>
                            <u-icon name="phone" size="32" color="#909399" class="input-icon"></u-icon>
                        </template>
                    </u-input>
                </u-form-item>

                <!-- 密码 -->
                <u-form-item label="密码" prop="password">
                    <u-input v-model="form.password" :type="isPasswordVisible ? 'text' : 'password'"
                        placeholder="请输入密码">
                        <template #prefix>
                            <u-icon name="lock" size="32" color="#909399" class="input-icon"></u-icon>
                        </template>
                        <template #suffix>
                            <u-icon :name="isPasswordVisible ? 'eye-fill' : 'eye'" size="32" color="#909399"
                                @click="togglePasswordVisibility"></u-icon>
                        </template>
                    </u-input>
                </u-form-item>
            </u-form>

            <!-- 登录按钮 -->
            <u-button type="primary" @click="handleLogin" :loading="isLoading" class="login-button"
                :disabled="isLoading">登录</u-button>

            <!-- 忘记密码 / 注册链接 -->
            <view class="login-actions">
                <u-button type="text" @click="goToForget" class="action-link"
                    style="margin-right:20rpx ;">忘记密码?</u-button>
                <u-button type="text" @click="goToRegister" class="action-link"
                    style="margin-left:20rpx">注册账号</u-button>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { loginAPI } from '../../../API/auth/login'
import { useUserStore } from '../../../store/modules/useUserStore'
import { useBindingStore } from '../../../store/modules/useBindingStore'



onMounted(() => {
    console.log("onMounted");

    console.log("userStore.isLoggedIn:", userStore.isLoggedIn);
    if (userStore.isLoggedIn) {
        const bindingStore = useBindingStore()
        uni.showToast({
            title: '您已登录!',
            icon: 'none'
        })
        let urls;
        if (userStore.userData.role == 'older') {
            urls = '/pages/role/older/home'
        } else {
            urls = '/pages/role/family/home'
        }
        bindingStore.fetchBindingList();

        // 跳转到主页，比如 profile 页面
        uni.reLaunch({
            url: urls
        })
    }
})

const userStore = useUserStore();

// 表单数据
const form = ref({
    phone: '',
    password: ''
})

// 状态管理
const isLoading = ref(false)
const isPasswordVisible = ref(false)
const formRef = ref(null)

// 页面配置
const pageTitle = '用户登录'
const headerBg = 'background-color: #007AFF'



// 自定义验证规则
const validateUsername = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请输入手机号'))
        return
    }

    // 区分手机号和用户名验证
    const phoneReg = /^1[3-9]\d{9}$/
    if (!phoneReg.test(value) && value.length < 6) {
        callback(new Error('用户名至少6位'))
    } else {
        callback()
    }
}

// 表单验证规则
const rules = {
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { validator: validateUsername, trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '至少输入6个字符', trigger: 'blur' },
        // { 
        //     pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{6,}$/, 
        //     message: '至少包含大小写字母和数字', 
        //     trigger: 'blur' 
        // }
    ]
}

// 切换密码可见性
const togglePasswordVisibility = () => {
    isPasswordVisible.value = !isPasswordVisible.value
}

// 登录处理
const handleLogin = async () => {
    try {
        // 表单验证
        const valid = await formRef.value.validate()
        if (!valid) return

        isLoading.value = true

        // 模拟登录请求
        const response = await loginAPI(form.value)


        if (response && response.code == 200) {
            console.log("登录成功---");
            uni.showToast({ title: '登录成功', icon: 'success' });

            // 先存储token再存储用户数据
            userStore.login(response.data.userData, response.data.token)

            console.log("登录成功");

            const bindingStore = useBindingStore()
            bindingStore.fetchBindingList();

            // 跳转到首页
            let urls;
            if (userStore.userData.role == 'older') {
                urls = '/pages/role/older/home'
            } else if(userStore.userData.role == 'family'){
                urls = '/pages/role/family/home'
            }else{
				urls = '/pages/role/doctor/home'
			}

            uni.navigateTo({
                url: urls,
                success() {
                    uni.showToast({
                        title: '登录成功',
                        icon: 'success',
                        duration: 2000
                    })
                }
            })


        } else {

            console.log('error login---', response.msg)
            throw new Error(response.msg)
        }
    } catch (error) {
        uni.showToast({
            title: `登录失败,${error.message}`,
            icon: 'none'
        })
        console.error('登录失败:', error)
    } finally {
        isLoading.value = false
    }
}

// 跳转忘记密码
const goToForget = () => {

}

// 跳转注册页面
const goToRegister = () => {
    console.log('goToRegister');

    uni.navigateTo({
        url: '/pages/common/auth/register'
    })
}
</script>

<style lang="scss" scoped>
.login {
    background-color: #f5f5f5;
    min-height: 100vh;
    display: flex;
    flex-direction: column;

    .login-header {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 40rpx 0;

        .login-header-logo {
            width: 240rpx;
            height: 240rpx;

            image {
                width: 100%;
                height: 100%;
                border-radius: 16rpx;
            }
        }
    }

    .login-form {
        flex: 1;
        padding: 20rpx 40rpx;
        margin-top: 20rpx;
        background-color: #fff;
        border-top-left-radius: 24rpx;
        border-top-right-radius: 24rpx;
    }

    .input-icon {
        margin-right: 20rpx;
    }

    .login-button {
        margin-top: 40rpx;
    }

    .login-actions {
        display: flex;
        justify-content: space-between;
        margin-top: 30rpx;


        padding: 0 20rpx;
        font-size: 20rpx;

        .action-link {
            color: #007AFF;
            padding: 10rpx 20rpx;
        }
    }
}
</style>